var app = getApp();
var c = require("../../lib/common.js");
var cf = require('../../lib/config.js');
var upimg = require('../../lib/upimg.js');
var im = require('../../lib/webim_wx.js');
var imhandler = require('../../lib/webim_handler.js');
var md5 = require('../../lib/md5.js');
Page({
  // 
  /**
   * 页面的初始数据
   */
  data: {
    img: 0,
    toView: 'red',
    scrolly: true,
    value: 0,
    focus: false,
    scrollTop: 300,
    newsn: [],
    hiddeninfo: true,
    starl: [1, 1, 1, 1, 1],
    starld: [1, 1, 1, 1, 1],
    path: '',
    listlength: 0,
    prepage: 1,
    scrollTop: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(option) {
    wx.showLoading({
      title: '加载...',
    })
    var imtop = app.imtop;
    var that = this;
    var did = option.did;
    wx.setNavigationBarTitle({
      title: did
    })
    var uid = imtop + wx.getStorageSync('userinfo').id;
    this.setData({
      did: did,
      uid: uid
    });
    c.loginVer(that, function(t) {
      t.gettalkinfo(did);
    });
  },

  gettalkinfo: function(did) {
    var uid = this.data.uid;
    var that = this;
    that.setData({
      did: did
    })
    //登录腾讯IM
    c.ajax(
      cf.doctor_hostapi + 'Im/getLoginInfo', {
        uid: uid
      },
      res => {
        var loginInfo = res.data.data;
        //1v1单聊的话，一般只需要 'onConnNotify' 和 'onMsgNotify'就行了。
        //监听连接状态回调变化事件
        var onConnNotify = function(resp) {
          var info;
          switch (resp.ErrorCode) { //链接状态码
            case im.CONNECTION_STATUS.ON:
              im.Log.warn('建立连接成功: ' + resp.ErrorInfo);
              console.log('建立连接成功: ' + resp.ErrorInfo);
              break;
            case im.CONNECTION_STATUS.OFF:
              info = '连接已断开，无法收到新消息，请检查下您的网络是否正常: ' + resp.ErrorInfo;
              im.Log.warn(info);
              console.log(info);
              break;
            case im.CONNECTION_STATUS.RECONNECT:
              info = '连接状态恢复正常: ' + resp.ErrorInfo;
              console.log(info);
              im.Log.warn(info);
              break;
            default:
              im.Log.error('未知连接状态: =' + resp.ErrorInfo); //错误信息
              console.log(info);
              break;
          }
        };

        //监听新消息事件     注：其中参数 newMsgList 为 webim.Msg 数组，即 [webim.Msg]。
        // newMsgList 为新消息数组，结构为[Msg]
        var onMsgNotify = function(newMsgList) {
          if (uid != fromAccount) {
            console.log('newMsgListnewMsgListnewMsgList');
            var newsn = that.data.newsn;
            var selToID = did;
            var sess, newMsg;
            //获取所有聊天会话
            var sessMap = im.MsgStore.sessMap();
            var newsns = [];
            var length = '';
            var TIMSoundElem = '';
            var did = that.data.did;
            var type = newMsgList[0]['elems'][0]['type'];
            if (type == 'TIMImageElem') {
              console.log('TIMImageElem');
              console.log(newMsgList[0]['elems'][0]['content']['ImageInfoArray']);
              var img = newMsgList[0]['elems'][0]['content']['ImageInfoArray'][0]['url'];
              var text = '';
            } else if (type == 'TIMTextElem' || type == 'TIMFaceElem') {
              var text = newMsgList[0]['elems'];
              var img = '';
            } else if (type == 'TIMSoundElem') {
              console.log();
              TIMSoundElem = newMsgList[0]['elems'][0]['content']['downUrl'];
              length = newMsgList[0]['elems'][0]['content']['second'];
            }

            console.log(text);
            newsns = {
              'fromAccount': did,
              'fromAccountNick': did,
              'type': type,
              'text': text,
              'img': img ? img : '',
              'TIMSoundElem': TIMSoundElem ? TIMSoundElem : '',
              'length': length ? length : ''
            }
            var length = newsn.length;
            newsn[length] = newsns;

            that.setData({
              newsn: newsn
            });

            var listlength = this.data.listlength;
            if (listlength < 10) {
              this.setData({
                listlength: listlength + 1
              })
            } else {
              this.pageScrollToBottom();
            }
            // return;
            // for (var j in newMsgList) { //遍历新消息
            //   newMsg = newMsgList[j];
            //   if (newMsg.getSession().id() == selToID) { //为当前聊天对象的消息
            //     var selSess = newMsg.getSession();
            //     console.log('aaaabbbbccccddddffff');
            //     console.log(newMsg);
            //     //在聊天窗体中新增一条消息
            //     //console.warn(newMsg);
            //     that.addMsg(newMsg);
            //   }
            // }
            // 消息已读上报，以及设置会话自动已读标记
            // im.setAutoRead(selSess, true, true);
            // for (var i in sessMap) {
            //   sess = sessMap[i];
            //   if (selToID != sess.id()) { //更新其他聊天对象的未读消息数
            //     updateSessDiv(sess.type(), sess.id(), sess.unread());
            //   }
            // }
          }


          
        }

        var listener = {
          "onConnNotify": onConnNotify, //监听连接状态回调变化事件,必填
          // , "jsonpCallback": jsonpCallback//IE9(含)以下浏览器用到的 jsonp 回调函数，
          // ,
          "onMsgNotify": onMsgNotify, //监听新消息(私聊，普通群(非直播聊天室)消息，全员推送消息)事件，必填
          // , "onBigGroupMsgNotify": onBigGroupMsgNotify//监听新消息(直播聊天室)事件，直播场景下必填
          // , "onGroupSystemNotifys": onGroupSystemNotifys//监听（多终端同步）群系统消息事件，如果不需要监听，可不填
          // , "onGroupInfoChangeNotify": onGroupInfoChangeNotify//监听群资料变化事件，选填
          // , "onFriendSystemNotifys": onFriendSystemNotifys//监听好友系统通知事件，选填
          // , "onProfileSystemNotifys": onProfileSystemNotifys//监听资料系统（自己或好友）通知事件，选填
          // , "onKickedEventCall": onKickedEventCall//被其他登录实例踢下线
          // , "onC2cEventNotifys": onC2cEventNotifys//监听 C2C 系统消息通道
        };
        var data = {
          'MaxCnt': 10
        }
        console.log('loginInfo');
        console.log(loginInfo);
        imhandler.sdkLogin(loginInfo, listener);
        return;

      }
    )



    var that = this;
    that.setData({
      height: wx.getSystemInfoSync().windowHeight - 180,
      addheight: (wx.getSystemInfoSync().windowHeight - 100) / 10
    })
    console.log('heightheightheightheight');
    console.log(wx.getSystemInfoSync().windowHeight);
    var that = this;
    setTimeout(function() {
      that.getC2CHistoryMsgs(0);
      that.pageScrollToBottom();
    }, 2000)
  },
  getC2CHistoryMsgs(timeinfo) {
    var did = this.data.did;
    var addheight = this.data.addheight;
    var that = this;
    var newsn = this.data.newsn;
    var height = this.data.height;
    var options = {

      'Peer_Account': did, //指定的好友帐号

      'MaxCnt': 10, //拉取的消息数目
      'LastMsgTime': timeinfo, //上一次拉取的时间  在第一次拉去消息的时候，这里必须为0
      'MsgKey': ''
    }

    im.getC2CHistoryMsgs(options, function(res) {
      var listlengthnew = that.data.listlength;
      var MsgList = res.MsgList;
      var bottomlegth = MsgList.length;
      var listlengthadd = MsgList.length + listlengthnew;
      console.log(listlengthadd);
      that.setData({
        listlength: listlengthadd
      })
      if (typeof(res.MsgList[0]) != 'undefined') {
        var lasttime = res.MsgList[0]['time'] - 1;
        var newsninfo = [];
        var sMsgListsinfo = res.MsgList;
        var fromAccount = '';
        var fromAccountNick = '';
        var type = '';
        var text = '';
        var img = [];
        var scrollheight = that.data.height;
        var addheight = that.data.addheight;
        var forheight = 0;
        var TIMSoundElem = '';
        var length = '';
        for (var i = 0; i < sMsgListsinfo.length; i++) {
          fromAccount = sMsgListsinfo[i]['fromAccount'];
          fromAccountNick = sMsgListsinfo[i]['fromAccountNick'];
          type = sMsgListsinfo[i]['elems'][0]['type'];
          text = sMsgListsinfo[i]['elems'];
          if (type == 'TIMImageElem') {
            img = sMsgListsinfo[i]['elems'][0]['content']['ImageInfoArray'][2]['url'];
          } else {
            img = 'no';
          }
          if (type == 'TIMSoundElem') {
            TIMSoundElem = sMsgListsinfo[i]['elems'][0]['content']['downUrl'];
            length = sMsgListsinfo[i]['elems'][0]['content']['second'];
          }
          newsninfo[i] = {
            'fromAccount': fromAccount,
            'fromAccountNick': fromAccountNick,
            'type': type,
            'text': text,
            'img': img,
            'TIMSoundElem': TIMSoundElem ? TIMSoundElem : '',
            'length': length ? length : '',
          }
          forheight += addheight;
        };
        if (timeinfo == 0) {
          var heightall = scrollheight + 10;
        } else {
          var heightall = scrollheight + forheight;
        }
        var newsninfon = newsninfo.concat(newsn)
        console.log('forheight----' + heightall);
        that.setData({
          newsn: newsninfon,
          lasttime: lasttime,
          height: heightall
        })

        if (timeinfo == 0) {
          wx.pageScrollTo({
            scrollTop: heightall + 100,
            duration: 0
          })
        } else {
          console.log('addheightaddheight');
          console.log(addheight);
          console.log(bottomlegth);
          wx.pageScrollTo({
            scrollTop: addheight * (bottomlegth - 1),
            duration: 0
          })
        }
      }
      wx.hideLoading();
    });


  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },
  onPageScroll: function(e) { // 获取滚动条当前位置
    console.log(111);
    var scrollTop = e.scrollTop; //获取滚动条当前位置的值
    console.log(scrollTop);
    if (scrollTop == 0) {
      var time = this.data.lasttime;
      console.log('time');
      console.log(time);
      if (time) {
        wx.showLoading({
          title: '...',
        })
        this.getC2CHistoryMsgs(time)
      }
    };
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  onMsgNotify: function() {
    var that = this;

    // var onMsgNotify = function(newMsgList) {
    //   var newsn = that.data.newsn;
    //   var selToID = '1';
    //   var sess, newMsg;
    //   //获取所有聊天会话
    //   var sessMap = im.MsgStore.sessMap();
    //   var newsns = [];
    //   var type = newMsgList[0]['elems'][0]['type'];
    //   if (type == 'TIMImageElem') {
    //     var img = newMsgList[0]['elems'][0]['content']['ImageInfoArray'][2]['url'];
    //     var text = '';
    //   } else if (type == 'TIMTextElem') {
    //     var text = newMsgList[0]['elems'][0]['content']['text'];
    //     var img = '';
    //   }
    //   newsns = {
    //     'fromAccount': '5',
    //     'fromAccountNick': '小王',
    //     'type': type,
    //     'text': text,
    //     'img': img ? img : ''
    //   }
    //   var length = newsn.length;
    //   newsn[length] = newsns;
    //   console.log(newsn);
    //   that.setData({
    //     newsn: newsn
    //   });

    // }
  },
  sendMsg: function(input) {
    var inputarray = [{
      'type': 'TIMTextElem',
      'content': {
        'text': input
      }
    }];
    var uid = this.data.uid;
    var did = this.data.did;
    var that = this;
    var msg = inputarray;
    var img = '';
    console.log('diddid');
    console.log(did);
    var info = imhandler.onSendMsg(input, '', did);
    var newsn = that.data.newsn;
    var newsns = [];
    newsns = {
      'fromAccount': uid,
      'fromAccountNick': uid,
      'type': 'TIMTextElem',
      'text': msg,
      'img': img ? img : ''
    };
    var length = newsn.length;
    newsn[length] = newsns;
    that.setData({
      newsn: newsn
    });
  },
  inputinfo: function(e) {
    var value = e.detail.value;
    if (value) {
      this.setData({
        value: 1,
        input: value
      })
    } else {
      this.setData({
        value: 0
      })
    }
  },
  send: function() {
    var listlength = this.data.listlength;
    var input = this.data.input;
    this.sendMsg(input);
    this.setData({
      value: 0,
      inputvalue: '',
      focus: true,
      img: 0
    });
    if (listlength < 10) {
      this.setData({
        listlength: listlength + 1
      })
    } else {
      this.pageScrollToBottom();
    }
  },
  clickimg: function(e) {
    var url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: [url] // 需要预览的图片http链接列表
    })
  },
  // 滚动最底部
  pageScrollToBottom: function() {
    var heightinfo = this.data.height;
    var addheight = this.data.addheight;
    console.log('pageScrollToBottompageScrollToBottompageScrollToBottompageScrollToBottom');
    console.log(heightinfo);
    this.setData({
      height: heightinfo + addheight
    })
    var heightinfoall = heightinfo + addheight;
    wx.pageScrollTo({
      scrollTop: 99999,
      duration: 0
    })
    // }).exec()
  },
  tiao: function() {
    console.log(111111);
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  jishao: function() {
    var img = this.data.img == 0 ? 1 : 0;
    this.setData({
      img: img
    })
  },
  //发送图片相册
  sendPic: function() {
    var path = 'talk/' + new Date().getTime() + '.png';
    var that = this;
    var i;
    var returninfo = upimg.simpleUpload(
      path,
      function(res) {
        console.log('sendPicsendPic');
        console.log(res);
        for (i = 0; i < res.length; i++) {
          that.sendPicApi(res[i]['imgLocation']);
        }
      },
      6
    );
  },
  //发送图片照相机
  paisendPic: function() {
    var path = 'talk/' + new Date().getTime() + '.png';
    var that = this;
    var i;
    var returninfo = upimg.simpleUpload(
      path,
      function(res) {
        setTimeout(function() {
          for (i = 0; i < res.length; i++) {
            that.sendPicApi(res[i]['imgLocation']);
          }
        }, 1000)
      },
      6,
      'camera'
    );
  },
  upper: function(e) {
    console.log('upper');
    console.log(e);
  },
  sendPicApi(url) {
    var timestamp1 = Date.parse(new Date()) + Math.random();;
    console.log(timestamp1);
    var md5info = md5.hexMD5(String(timestamp1));
    console.log(md5info);
    var md5num = md5info.toUpperCase();
    console.log(md5num);
    var that = this;
    var newsns = [];
    var newsn = that.data.newsn;
    var selToID = this.data.did;
    var uid = this.data.uid;
    var selSess = '';
    var listlength = this.data.listlength;

    var images = {
      "ActionStatus": "OK",
      "From_Account": uid,
      "To_Account": "1",
      "App_Version": "2.1",
      "Appid": 1400133121,
      "Seq": 9971632,
      "Random": 4091267451,
      "Timestamp": 1548298613,
      "ErrorCode": 0,
      "IsRejectRetry": 0,
      "ErrorInfo": "",
      "Next_Offset": 0,
      "IsFinish": 1,
      "File_UUID": "15614_" + md5num,
      "URL_INFO": [{
        "PIC_TYPE": 2,
        "DownUrl": url,
        "PIC_Width": 198,
        "PIC_Height": 198,
        "PIC_Size": 0
      }]
    };

    newsns = {
      'fromAccount': uid,
      'fromAccountNick': uid,
      'type': 'TIMImageElem',
      'text': '',
      'img': url
    }
    console.log('yyyyyyyyyyyyuuuuuuuuuuuuu');
    var length = newsn.length;
    newsn[length] = newsns;
    console.log('kkkkkkkkkkkllllllllllllll');
    console.log(newsn);

    that.setData({
      newsn: newsn,
      img: 0
    });


    selSess = new im.Session('C2C', selToID, selToID, 'img/friend.jpg',
      Math.round(new Date().getTime() / 1000));

    var msg = new im.Msg(selSess, true);
    var images_obj = new im.Msg.Elem.Images(images.File_UUID);
    for (var i in images.URL_INFO) {
      var img = images.URL_INFO[i];
      var newImg;
      var type;
      switch (img.PIC_TYPE) {
        case 1: //原图
          type = 1; //原图
          break;
        case 2: //小图（缩略图）
          type = 3; //小图
          break;
        case 4: //大图
          type = 2; //大图
          break;
      }
      newImg = new im.Msg.Elem.Images.Image(type, img.PIC_Size, img.PIC_Width,
        img.PIC_Height, img.DownUrl);
      images_obj.addImage(newImg);
    }
    msg.addImage(images_obj);

    //调用发送图片接口
    im.sendMsg(msg, function(resp) {
      that.setData({
        img: 0
      })
      console.log('pageScrollToBottompageScrollToBottom');
      if (listlength < 10) {
        that.setData({
          listlength: listlength + 1
        })
      } else {
        that.pageScrollToBottom();
      }
      // curMsgCount++;
    }, function(err) {
      // alert(err.ErrorInfo);
    });
  },
  staradd: function(e) {
    console.log(e)
    var starl = [];
    var starb = [];
    var num = e.currentTarget.dataset.num;

    for (var i = 0; i < num; i++) {
      starl[i] = 1;
    }
    for (var i = 0; i < (5 - num); i++) {
      starb[i] = 1;
    }
    this.setData({
      starl: starl,
      starb: starb
    });
  },
  stardee: function(e) {
    var starb = [];
    var num = e.currentTarget.dataset.num;
    console.log(num);
    var starl = this.data.starl;
    var lcount = starl.length;
    //在亮星的基础上网上添加
    for (var i = lcount; i <= lcount + num; i++) {
      starl[i] = 1;
    }
    var lcountdel = starl.length;
    for (var i = 0; i < (5 - lcountdel); i++) {
      starb[i] = 1;
    }
    this.setData({
      starl: starl,
      starb: starb
    });
  },
  title: function(e) {
    this.data.title = e.detail.value;
  },
  sendpl: function() {
    var did = this.data.did;
    var that = this;
    var starl = this.data.starl;
    var title = this.data.title;
    var starnum = starl.length;
    var uid = this.data.uid;
    var goods_id = this.data.goods_id;
    c.ajax(
      cf.hostapi + 'Im/AddComment', {
        star: starnum,
        uid: uid,
        did: did,
        content: title
      },
      res => {
        var page = that.data.page;
        if (res.data.status == 'success') {
          wx.showToast({
            title: '发表成功!',
            image: '/images/dui.png'
          })
          setTimeout(function() {
            wx.navigateBack({
              delta: page - 1,
            })
          }, 1000)
        }
      }
    )
  },
  deletes: function() {
    this.setData({
      hiddeninfo: true,
    })
  },
  commentwww: function() {

    this.setData({
      hiddeninfo: false
    })
  },
  tIMSoundElemclick: function(e) {
    var pathold = this.data.path;
    var path = e.currentTarget.dataset.url;
    var that = this;
    this.setData({
      path: path
    })
    const innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.autoplay = true;
    innerAudioContext.seek(0);
    innerAudioContext.src = path;
    innerAudioContext.onPlay(() => {
      console.log('patholdpatholdpathold');
      console.log(pathold);
      const innerAudioContexsst = wx.createInnerAudioContext();
      innerAudioContexsst.destroy();
      innerAudioContexsst.src = pathold;
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  }
})